package com.efounder.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AlertDialog;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.http.RequestHttpDataUtil;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.ospmobilelib.R;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.LogOutUtil;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.start.LoginCheckManager;
import com.utilcode.util.LogUtils;

import net.sf.json.JSONObject;

import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 使用restful方式登录应用
 */
public class LoginByRestFul implements LoginByRestFulInterface {
    private String userName;
    private String passWord;
    private Context mContext;
    private String chatUserID;
    private String chatPassword;

    private int loginType;
    private String loginSuccessResponse;

    private OpenPlanetLoginListener openPlanetLoginListener;
    /**
     * 请求成功
     */
    private static final int RESPONSE_NUM_SUCCESS = 0;
    /**
     * 网络或服务器异常
     */
    private static final int RESPONSE_NUM_NETWORK_ERROR = 2;
    /**
     * 未配置请求地址
     */
    private static final int RESPONSE_NUM_NO_URL = 3;


    /**
     * @param loginType 0:登录页 1：非登录页 2：手动检查更新
     *                  {@link  LoginCheckManager#TYPE_LOGIN}
     */
    public LoginByRestFul(int loginType) {
        this.loginType = loginType;
    }

    /**
     * 第一步 登录
     *
     * @param context
     * @param
     */

    @Override
    public void loginBegin(Context context, String userName1, final String passWord1) {
        HashMap<String, String> params = new HashMap<>();
        params.put("userId", userName1);
        params.put("passWord", passWord1);
        loginBegin(context, params);
    }

    /**
     * 第一步 登录（参数param 可以用于山大智信微信登录）
     *
     * @param context
     * @param params
     */
    @Override
    public void loginBegin(Context context, HashMap<String, String> params) {
        mContext = context;
        userName = params.get("userId");
        passWord = params.get("passWord");
        if (userName == null) {
            LogUtils.e("登录的用户名必须使用 key =userId这个字段名！！！");
            return;
        }
        params.put("appId", EnvironmentVariable.getProperty("APPID"));
        params.put("deviceType", "android");
        showLoginLoading();
        //请求服务器
        GetHttpUtil.loginByRestFul(context, params, new RequestHttpDataUtil.LoginByRestFulCallBack() {
            @Override
            public void loginResponse(int responsenum, String response) {
                parseRestfulLoginResponse(responsenum, response);
            }
        });
    }

    /**
     * 显示登录的loading框
     */
    protected void showLoginLoading() {
        if (loginType == LoginCheckManager.TYPE_CHECK_VERSION) {
            LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_checking));
        } else if (loginType == LoginCheckManager.TYPE_LOGIN) {
            LoadingDataUtilBlack.show(mContext, ResStringUtil.getString(R.string.common_text_islogining));
        }
    }

    /**
     * 第二步 解析登录返回数据
     *
     * @param responsenum 成功码
     * @param response    数据
     */
    private void parseRestfulLoginResponse(int responsenum, String response) {
        LoadingDataUtilBlack.dismiss();

        if (responsenum == RESPONSE_NUM_SUCCESS) {
            //服务器正常返回
            //{"limits":[],"result":"success","appUpgrade":{"android":{"appFile":{"des":"1.修复扫码加群闪退的问题","path":"https://mobile.solarsource.cn/ospstore/OSPMobileLiveAPP/OSPMobileLiveApp.apk","version":"1.2.47"},"appResource":{"des":"","path":"","version":"0.0.53"}}},"user":{"imUserId":574,"imUserPassWord":"123456","userId":"18663788773","userName":"臧言科"}}
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.fromObject(response);
            } catch (Exception e) {
                e.printStackTrace();
                if (openPlanetLoginListener != null) {
                    openPlanetLoginListener.loginFail(ResStringUtil.getString(R.string.common_text_chcek_version_fail));
                }
                return;
            }
            String result = jsonObject.optString("result", "fail");
            if (result.equals("success")) {
                //保存登录信息，方便其他客户使用
                EnvironmentVariable.setProperty("LoginInfo", response);
                loginSuccessResponse = response;
                APKUpdateControl apkUpdateControl = new APKUpdateControl();
                boolean update = apkUpdateControl.CheckAPKVerion(mContext, response, checkVersionHandler);

                if (loginType == LoginCheckManager.TYPE_CHECK_VERSION && !update) {
                    ToastUtil.showToast(mContext, R.string.common_text_app_is_newest);
                }
                //数字视觉云的信息保存
                //  dealOtherInfo(jsonObject);

                if (jsonObject.containsKey("user")) {
                    String user = jsonObject.optString("user", "");
                    com.alibaba.fastjson.JSONObject userjsonObject = JSON.parseObject(user);
                    gxVariable(userjsonObject);
                }

                if (jsonObject.containsKey("extraInfo")) {
                    String extraInfo = jsonObject.optString("extraInfo", "");
                    EnvironmentVariable.setProperty("extraInfo", extraInfo);
                } else {
                    EnvironmentVariable.setProperty("extraInfo", "");

                }
            } else {
                String msg = jsonObject.optString("msg", "");
                loginFail(msg);
            }

        } else if (responsenum == RESPONSE_NUM_NETWORK_ERROR) {
            //网络出错
            if (loginType == LoginCheckManager.TYPE_LOGIN) {
                //response =网络连接失败
                showDialog(response + "");
            } else if (loginType == LoginCheckManager.TYPE_CHECK_VERSION) {
//                ToastUtil.showToast(mContext, R.string.common_text_login_fail_network);
                ToastUtil.showToast(mContext, R.string.common_text_chcek_version_fail);
            }
            if (openPlanetLoginListener != null) {
                openPlanetLoginListener.loginFail(ResStringUtil.getString(R.string.common_text_chcek_version_fail));
            }
        } else if (responsenum == RESPONSE_NUM_NO_URL) {
            //未设置登录地址,生产环境不会出现这个问题的
            showDialog("请设置登录地址");
        }
    }

    /**
     * 登录失败
     *
     * @param msg 失败的提示信息
     */
    protected void loginFail(String msg) {
        if (loginType == LoginCheckManager.TYPE_LOGIN) {
            //fixme 登录页调用，提示登录失败
            if (!TextUtils.isEmpty(msg)) {
                showDialog(msg + "");
            } else {
                showDialog(ResStringUtil.getString(R.string.common_text_login_fail_please_wait));
            }
        } else {
            //fixme 非登录页调用，提示登录失效
            if (openPlanetLoginListener != null) {
                openPlanetLoginListener.loginFail(ResStringUtil.getString(R.string.common_text_chcek_version_fail));
            }
            try {
                //提示登陆过期
                LogoutEvent logoutEvent = new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE);
                LogOutUtil.notifyOffline(logoutEvent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理其他信息的保存（目前是数字视觉云，已经不用了）
     *
     * @param jsonObject
     */
    @Deprecated
    protected void dealOtherInfo(JSONObject jsonObject) {
        //-------数字视觉云-------------
        if (jsonObject.containsKey("accessToken")) {
            EnvironmentVariable.setProperty("accessToken", jsonObject.getString("accessToken"));
        }
        if (jsonObject.containsKey("accessKeyId")) {
            EnvironmentVariable.setProperty("accessKeyId", jsonObject.getString("accessKeyId"));
        }
        if (jsonObject.containsKey("accessKeySecret")) {
            EnvironmentVariable.setProperty("accessKeySecret", jsonObject.getString("accessKeySecret"));
        }
        if (jsonObject.containsKey("play_key")) {
            EnvironmentVariable.setProperty("play_key", jsonObject.getString("play_key"));
        }
        if (jsonObject.containsKey("api_key")) {
            EnvironmentVariable.setProperty("api_key", jsonObject.getString("api_key"));
        }

        if (jsonObject.has("limits")) {
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.optString("limits", "[]"));
            if (jsonArray.size() == 0) {
                EnvironmentVariable.setProperty("gnqx", null);
                return;
            }
            //String gnqxString = "";
            StringBuffer gnqxBuffer = new StringBuffer("");
            for (int i = 0; i < jsonArray.size(); i++) {
                String gnqx = jsonArray.getString(i);
                gnqxBuffer.append(gnqx).append(";");
            }
            //设置权限
            EnvironmentVariable.setProperty("gnqx", gnqxBuffer.toString());
        }
        //-------数字视觉云-------------
    }

    /**
     * 检查更新的handler
     */
    protected CheckVersionHandler checkVersionHandler = new CheckVersionHandler();

    private class CheckVersionHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                case 2:
                    if (loginType == LoginCheckManager.TYPE_LOGIN || loginType == 3) {
                        //只有在登录界面的时候才会检查im用户
                        // LoadingDataUtilBlack.show(mContext);
                        //支持消息服务
                        if (EnvSupportManager.isSupportIM()) {
                            CheckIM(loginSuccessResponse);
                        } else {
                            checkGNQX(loginSuccessResponse);
                            mHandler.sendEmptyMessage(0);
                        }
                    } else {
                        if (loginType == LoginCheckManager.TYPE_NOT_LOGIN) {
                            if (openPlanetLoginListener != null) {
                                openPlanetLoginListener.loginSuccess(loginSuccessResponse);
                            }
                        }
                        //检查并保存功能权限
                        checkGNQX(loginSuccessResponse);
                    }


                    break;

                default:

                    break;
            }
        }
    }

    /**
     * 第四步 检查是否是微信用户
     */
    private void CheckIM(String result) {

        boolean isIMUser = isIMUser(result);
        if (isIMUser) {
            //检查权限
            //铁工独有的功能权限，上面是平台的功能权限检查。
            checkGNQX(result);
            mHandler.sendEmptyMessage(0);

        } else {
            //FIXME 由于铁工没有注册功能，先屏蔽掉-- 跳转到注册界面，并传值
//			Intent intent = new Intent(mContext, RegisterActivity.class);
//			intent.putExtra("userName",userName);
//			intent.putExtra("password",passWord);
//			mContext.startActivity(intent);
        }

    }

    /**
     * @param result
     * @return
     */
    private boolean isIMUser(String result) {
        //判断是否注册
//		Map<?, ?> responseMap = (Map<?, ?>) result.getResponseMap();
//		EFDataSet weChatDataSet = (EFDataSet) responseMap.get("extrawx");
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
        String user = jsonObject.getString("user");
        com.alibaba.fastjson.JSONObject userjsonObject = JSON.parseObject(user);

        String imUserId = userjsonObject.getString("imUserId");


        if (null == imUserId || imUserId.equals("")) {
            showDialog(ResStringUtil.getString(R.string.login_user_not_exist));
            return false;
        } else {
            //{"imUserId":574,"imUserPassWord":"123456","userId":"18663788773","userName":"臧言科"}}

            String imUserPassWord = userjsonObject.getString("imUserPassWord");
            chatUserID = imUserId;
            chatPassword = imUserPassWord;
            String userId = userjsonObject.getString("userId");
            String userName1 = userjsonObject.getString("userName");
            chatPassword = imUserPassWord;
            EnvironmentVariable.setUserName(userName);

            EnvironmentVariable.setPassword(passWord);
            gxVariable(userjsonObject);


        }

//		//TODO 如果是普光应用,需要保存以下信息,根据配置文件决定是否保存
//		if ("true".equals(EnvironmentVariable.getProperty(KEY_SAVE))){
//			saveUserInfo(weChatRowSet);
//		}
        return true;
    }

    private void gxVariable(com.alibaba.fastjson.JSONObject userjsonObject) {
        //共享参数
        EnvironmentVariable.setProperty("F_UNITID", userjsonObject.getString("ext0"));
        EnvironmentVariable.setProperty("UNITID_MC", userjsonObject.getString("ext1"));
        EnvironmentVariable.setProperty("F_BMBH", userjsonObject.getString("ext2"));
        EnvironmentVariable.setProperty("BMMC", userjsonObject.getString("ext3"));
        EnvironmentVariable.setProperty("F_ZZJG", userjsonObject.getString("ext4"));
        EnvironmentVariable.setProperty("ZZJGMC", userjsonObject.getString("ext5"));
        EnvironmentVariable.setProperty("F_SYZT", userjsonObject.getString("ext6"));
        EnvironmentVariable.setProperty("F_CRDATE", userjsonObject.getString("ext7"));
        EnvironmentVariable.setProperty("F_OPNAME", userjsonObject.getString("ext8"));
        EnvironmentVariable.setProperty("F_OPUSER", userjsonObject.getString("ext9"));
        EnvironmentVariable.setProperty("F_NOTE", userjsonObject.getString("ext10"));
        EnvironmentVariable.setProperty("F_SEX", userjsonObject.getString("ext11"));
        EnvironmentVariable.setProperty("F_TEL", userjsonObject.getString("ext12"));
        EnvironmentVariable.setProperty("F_EMAIL", userjsonObject.getString("ext13"));
        EnvironmentVariable.setProperty("F_FAX", userjsonObject.getString("ext14"));
        EnvironmentVariable.setProperty("F_POSTCODE", userjsonObject.getString("ext15"));
        EnvironmentVariable.setProperty("F_ADDRESS", userjsonObject.getString("ext16"));
        EnvironmentVariable.setProperty("F_XZQH", userjsonObject.getString("ext17"));
        EnvironmentVariable.setProperty("F_ZGLX", userjsonObject.getString("ext18"));
        EnvironmentVariable.setProperty("F_BXJB", userjsonObject.getString("ext19"));
        EnvironmentVariable.setProperty("F_GRZH", userjsonObject.getString("ext20"));
        EnvironmentVariable.setProperty("F_HRBH", userjsonObject.getString("ext21"));
        EnvironmentVariable.setProperty("F_ID", userjsonObject.getString("ext22"));
        EnvironmentVariable.setProperty("F_HF", userjsonObject.getString("ext23"));
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //在微信登陆之前，存储用户名，密码
            //FIXME 在底层库用到getUserID方法，以后再修改
            EnvironmentVariable.setUserID(chatUserID);
            EnvironmentVariable.setProperty(CHAT_USER_ID, chatUserID);
            EnvironmentVariable.setProperty(CHAT_PASSWORD, chatPassword);
            Log.i("------", "EnvironmentVariable------" + EnvironmentVariable.getProperty(CHAT_USER_ID));
            Log.i("------", "EnvironmentVariable------" + EnvironmentVariable.getProperty(CHAT_PASSWORD));

            startMainActivity();
        }
    };


    private void startMainActivity() {
        try {
            LoadingDataUtilBlack.dismiss();
            String className = mContext.getResources().getString(R.string.from_group_backto_first);
            Class clazz = Class.forName(className);
            Intent myIntent = new Intent(mContext, clazz);
            myIntent.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级

            mContext.startActivity(myIntent);
            ((Activity) mContext).finish();
        } catch (Exception e) {
            e.printStackTrace();
        }

//        //ESPMobile处理
//        Intent intent1 = new Intent(mContext, TabBottomActivity.class);
//        intent1.putExtra("unDoCheck", "true");//从登录界面跳转无需再次检查是否升级
//        //intent1.putExtra("listobj", (Serializable) mainMenuList);
//        mContext.startActivity(intent1);
//        ((Activity) mContext).finish();
//        LoadingDataUtilBlack.dismiss();

    }

    private void checkGNQX(String result) {

        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(result);
        String limits = jsonObject.getString("limits");
        if (null == limits || limits.equals("")) {
            EnvironmentVariable.setProperty("gnqx", null);
            return;
        }

        JSONArray jsonArray = JSONArray.parseArray(limits);
        if (jsonArray.size() == 0) {
            EnvironmentVariable.setProperty("gnqx", null);
            return;
        }
        // String gnqxString = "无";
        StringBuffer gnqnBuffer = new StringBuffer(ResStringUtil.getString(R.string.login_nothing));
        for (int i = 0; i < jsonArray.size(); i++) {
            String gnqx = jsonArray.getString(i);
            //gnqxString = gnqxString + gnqx + ";";
            gnqnBuffer.append(gnqx).append(";");
        }
        //设置权限
//        EnvironmentVariable.setProperty("gnqx", gnqxString);
        EnvironmentVariable.setProperty("gnqx", gnqnBuffer.toString());

    }

    public void showDialog(String info) {
        new AlertDialog.Builder(mContext).
                setMessage(info).setTitle(R.string.common_text_hint).setNegativeButton(R.string.common_text_cancel, null)
                .setPositiveButton(R.string.common_text_confirm, null).show();
    }


    //todo 星际通讯登录调用，也可在别的地方使用(星际通讯登录不涉及imuser 用户，返回信息中没有用户信息)
    public interface OpenPlanetLoginListener {
        void loginSuccess(String response);

        void loginFail(String fail);
    }

    public void setOpenPlanetLoginListener(OpenPlanetLoginListener listener) {
        this.openPlanetLoginListener = listener;
    }
}
